package com.promise.jokerdream.ui.webview

import android.webkit.WebView
import android.net.Uri
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.ui.Alignment
import androidx.compose.ui.zIndex
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.promise.jokerdream.ui.drawer.FullScreenEdgeSwipeDrawer
import com.promise.jokerdream.ui.drawer.NavigationDrawerContent
import com.promise.jokerdream.ui.toolbar.ChromeStyleToolbar
import com.promise.jokerdream.ui.toolbar.PMBottomNavigation
import com.promise.jokerdream.ui.components.PMDialog
import com.promise.jokerdream.viewmodel.MainViewModel
import com.promise.jokerdream.viewmodel.SettingsViewModel
import com.promise.jokerdream.navigation.AppRoute
import com.promise.jokerdream.ui.overlay.GameFunctionBottomSheet
import com.promise.jokerdream.ui.overlay.GameFunction
import com.promise.jokerdream.ui.tower.KnightDreamDialog
import com.promise.jokerdream.utils.FontSizePreferenceManager

/**
 * WebView主屏幕
 */
@Composable
fun WebViewScreen(
    navController: NavController,
    viewModel: MainViewModel = viewModel(),
    onWebViewCreated: (WebView) -> Unit = {}
) {
    val context = LocalContext.current
    val drawerWidth = 280.dp
    val coroutineScope = rememberCoroutineScope()
    
    // 从ViewModel获取状态
    val currentUrl by viewModel.currentUrl.collectAsState()
    val webViewProgress by viewModel.webViewProgress.collectAsState()
    val canGoBack by viewModel.canGoBack.collectAsState()
    val canGoForward by viewModel.canGoForward.collectAsState()
    val currentAccount by viewModel.currentAccount.collectAsState()
    val isDrawerOpen by viewModel.isDrawerOpen.collectAsState()
    val fightProcessProgress by viewModel.fightProcessProgress.collectAsState()
    val isIncognitoEnabled by viewModel.isIncognitoEnabled.collectAsState()
    
    // 待执行的导航操作
    var pendingNavigation by remember { mutableStateOf<String?>(null) }
    
    // 游戏功能选择页面状态
    var showGameFunctionSheet by remember { mutableStateOf(false) }
    
    // 江湖长梦对话框状态
    var showKnightDreamDialog by remember { mutableStateOf(false) }
    
    // 搜索对话框状态
    var showSearchDialog by remember { mutableStateOf(false) }
    
    // 字体大小调整对话框状态
    var showFontSizeDialog by remember { mutableStateOf(false) }
    
    // 获取当前字体大小
    val currentFontSize = remember { 
        mutableStateOf(FontSizePreferenceManager.getFontSize(context)) 
    }
    
    // 获取用户账户信息（用于搜索对话框默认值）
    val settingsViewModel: SettingsViewModel = viewModel()
    val account by settingsViewModel.account.collectAsState()
    
    // 获取URL中的B_UID参数
    fun getBUIDFromUrl(): String? {
        return try {
            val uri = Uri.parse(currentUrl)
            uri.getQueryParameter("B_UID")
        } catch (e: Exception) {
            null
        }
    }
    
    // 处理搜索点击
    fun handleSearchClick() {
        showSearchDialog = true
    }
    
    // 处理导航抽屉中的路由点击
    fun handleDrawerRouteClick(route: String) {
        when (route) {
            "copy_cookie" -> {
                viewModel.closeDrawer()
                viewModel.copyCurrentCookie()
            }
            "clear_cookie" -> {
                viewModel.closeDrawer()
                viewModel.clearAllCookies()
            }
            "font_size" -> {
                viewModel.closeDrawer()
                // 更新当前字体大小
                currentFontSize.value = FontSizePreferenceManager.getFontSize(context)
                showFontSizeDialog = true
            }
            "toggle_incognito" -> {
                viewModel.toggleIncognitoMode()
                // 切换后关闭抽屉，让用户更直观地看到页面刷新
                viewModel.closeDrawer()
            }
            "account_management", "settings", "test_xml_parse" -> {
                // 设置待执行的导航操作
                pendingNavigation = route
                // 关闭抽屉，LaunchedEffect会监听到状态变化并执行导航
                viewModel.closeDrawer()
            }
            else -> {
                viewModel.closeDrawer()
                // 其他路由的处理逻辑
            }
        }
    }

    // 监听抽屉状态，当抽屉关闭时执行待执行的导航
    LaunchedEffect(isDrawerOpen) {
        if (!isDrawerOpen && pendingNavigation != null) {
            val route = pendingNavigation
            pendingNavigation = null // 清除待执行操作
            
            // 等待抽屉关闭动画完成
            kotlinx.coroutines.delay(300) // 300ms延迟，确保抽屉完全关闭
            
            when (route) {
                "account_management" -> {
                    navController.navigate(AppRoute.AccountManagement.route)
                }
                "settings" -> {
                    navController.navigate(AppRoute.Settings.route)
                }
                "test_xml_parse" -> {
                    navController.navigate(AppRoute.XmlParseTest.route)
                }
                // 可以添加其他需要导航的路由
            }
        }
    }
    // 使用稳定的key来确保WebView实例在页面切换时保持
    val webView = remember {
        // 优先从 ViewModel 获取现有 WebView
        viewModel.getWebView() ?: WebViewFactory.createWebView(
            context = context,
            callback = WebViewCallbackImpl(
                onPageFinished = { url -> 
                    viewModel.updateCurrentUrl(url)
                    // 更新导航状态
                    val currentWebView = viewModel.getWebView()
                    viewModel.updateNavigationState(
                        canBack = currentWebView?.canGoBack() ?: false,
                        canForward = currentWebView?.canGoForward() ?: false
                    )
                },
                onProgressChanged = { progress -> 
                    viewModel.updateProgress(progress)
                },
                onLoginDetected = { userId, username, cookie ->
                    viewModel.handleLoginDetected(userId, username, cookie)
                },
                onFightProcessProgress = { currentPage, totalPages ->
                    viewModel.updateFightProcessProgress(currentPage, totalPages)
                },
                onFightProcessCompleted = {
                    viewModel.clearFightProcessProgress()
                },
                onFightProcessCancelled = {
                    viewModel.clearFightProcessProgress()
                }
            )
        ).also { createdWebView ->
            viewModel.setWebView(createdWebView)
        }
    }
    
    // 确保 WebView 在 ViewModel 中正确设置
    LaunchedEffect(webView) {
        if (viewModel.getWebView() != webView) {
            viewModel.setWebView(webView)
        }
        // 调用WebView创建回调
        onWebViewCreated(webView)
    }
    
    // 处理返回手势 - 优先级：抽屉 > WebView > 应用退出
    BackHandler(enabled = true) {
        when {
            isDrawerOpen -> {
                // 如果抽屉打开，先关闭抽屉
                viewModel.closeDrawer()
            }
            webView.canGoBack() -> {
                // 如果WebView可以返回，让WebView处理
                viewModel.goBack()
            }
            else -> {
                // 如果WebView无法返回，退出应用到后台
                (context as? ComponentActivity)?.moveTaskToBack(true)
            }
        }
    }
    
    FullScreenEdgeSwipeDrawer(
        drawerWidth = drawerWidth,
        isDrawerOpen = isDrawerOpen,
        enableGesture = true,
        onDrawerStateChanged = { isOpen -> 
            if (isOpen) viewModel.openDrawer() else viewModel.closeDrawer()
        },
        onOpenDrawer = { viewModel.openDrawer() },
        onCloseDrawer = { viewModel.closeDrawer() },
        drawerContent = {
            NavigationDrawerContent(
                currentAccount = currentAccount,
                isIncognitoEnabled = isIncognitoEnabled,
                onItemClick = { route ->
                    handleDrawerRouteClick(route)
                }
            )
        }
    ) {
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
            // Chrome风格的紧凑导航栏
            ChromeStyleToolbar(
                currentUrl = currentUrl,
                onRefreshClick = { viewModel.refreshWebView() },
                onMenuClick = { viewModel.openDrawer() },
                onSearchClick = { handleSearchClick() },
                onUrlChange = { url -> viewModel.loadUrl(url) },
                progress = webViewProgress / 100f
            )
            
            // WebView 和进度条覆盖层
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {
                // WebView
                AndroidView(
                    factory = { webView },
                    update = { webViewInstance ->
                        // 确保 WebView 实例是最新的
                        // 这里不需要做任何操作，因为 webView 是 remember 的
                    },
                    modifier = Modifier.fillMaxSize()
                )
                
                // 战斗过程解析进度条 - 覆盖层
                fightProcessProgress?.let { (currentPage, totalPages) ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(color = MaterialTheme.colorScheme.primaryContainer)
                            .padding(horizontal = 16.dp, vertical = 8.dp)
                            .align(Alignment.TopStart)
                            .zIndex(2f),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Start
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            color = MaterialTheme.colorScheme.primary,
                            trackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "正在加载第 $currentPage/$totalPages 页乐斗过程",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                }
            }
            
            // 底部导航栏
            PMBottomNavigation(
                canGoBack = canGoBack,
                canGoForward = canGoForward,
                onBackClick = { viewModel.goBack() },
                onForwardClick = { viewModel.goForward() },
                onHomeClick = { viewModel.goHome() },
                onSettingsClick = {
                    navController.navigate(AppRoute.Settings.route)
                },
                onExecutionLogClick = {
                    navController.navigate(AppRoute.ExecutionLog.route)
                },
                onGameFunctionClick = {
                    // 显示游戏功能选择页面
                    showGameFunctionSheet = true
                }
            )
        }
        
        // 游戏功能选择页面
        if (showGameFunctionSheet) {
            GameFunctionBottomSheet(
                onDismiss = { showGameFunctionSheet = false },
                onFunctionClick = { function ->
                    showGameFunctionSheet = false
                    when (function) {
                        GameFunction.AUTO_PLAY -> {
                            // 导航到代玩页面
                            navController.navigate(AppRoute.AutoPlay.route)
                        }
                        GameFunction.BAG -> {
                            // 导航到背包页面
                            navController.navigate(AppRoute.Bag.route)
                        }
                        GameFunction.TOWER_FIGHT -> {
                            // 导航到斗神塔页面
                            navController.navigate(AppRoute.TowerFight.route)
                        }
                        GameFunction.KNIGHT_DREAM -> {
                            // 显示江湖长梦对话框
                            showKnightDreamDialog = true
                        }
                        GameFunction.WULIN_SEARCH -> {
                            // 导航到武林查区页面
                            navController.navigate(AppRoute.WuLinSearch.route)
                        }
                        GameFunction.ESCORT -> {
                            // 导航到劫镖页面
                            navController.navigate(AppRoute.Escort.route)
                        }
                        GameFunction.TERRITORY -> {
                            // 导航到问鼎页面
                            navController.navigate(AppRoute.Territory.route)
                        }
                        GameFunction.SNAP_UP -> {
                            // 导航到抢购页面
                            navController.navigate(AppRoute.SnapUp.route)
                        }
                        GameFunction.TIMER -> {
                            // 导航到定时任务页面
                            navController.navigate(AppRoute.Timer.route)
                        }
                        GameFunction.QUICK_EXCHANGE -> {
                            // 导航到快速兑换页面
                            navController.navigate(AppRoute.QuickExchange.route)
                        }
                        GameFunction.CUSTOM_TASK -> {
                            // 导航到自定义任务页面
                            navController.navigate(AppRoute.CustomTask.route)
                        }
                        GameFunction.ROB_TERRITORY -> {
                            // 导航到抢地盘页面
                            navController.navigate(AppRoute.RobTerritory.route)
                        }
                        GameFunction.FIGHT_FRIEND -> {
                            // 导航到乐斗好友页面
                            navController.navigate(AppRoute.FightFriend.route)
                        }
                    }
                }
            )
        }
        
        // 江湖长梦对话框
        KnightDreamDialog(
            show = showKnightDreamDialog,
            onDismiss = { showKnightDreamDialog = false },
            onConfirm = { config ->
                showKnightDreamDialog = false
                // 启动江湖长梦任务
                viewModel.startKnightDreamTask(config)
                // 跳转到执行记录页面
                navController.navigate(AppRoute.ExecutionLog.route)
            },
        )
        
        // 搜索对话框
        if (showSearchDialog) {
            var searchInput by remember { mutableStateOf(getBUIDFromUrl() ?: account?.userId ?: "") }
            
            // 每次显示对话框时更新初始值
            LaunchedEffect(showSearchDialog) {
                if (showSearchDialog) {
                    searchInput = getBUIDFromUrl() ?: account?.userId ?: ""
                }
            }
            
            PMDialog(
                show = showSearchDialog,
                title = "搜索企鹅信息",
                confirmText = "确认",
                cancelText = "取消",
                onDismiss = { showSearchDialog = false },
                onConfirm = {
                    if (searchInput.isNotEmpty()) {
                        showSearchDialog = false
                        navController.navigate("penguin_info/${searchInput.trim()}")
                    }
                }
            ) {
                OutlinedTextField(
                    value = searchInput,
                    onValueChange = { searchInput = it },
                    label = { Text("用户ID (puin)") },
                    placeholder = { Text("请输入用户ID...") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
        
        // 字体大小调整对话框
        FontSizeDialog(
            show = showFontSizeDialog,
            currentFontSize = currentFontSize.value,
            onDismiss = { 
                showFontSizeDialog = false
            },
            onFontSizeChange = { fontSize ->
                // 实时保存设置（拖动时立即保存，确保下次启动也能应用）
                FontSizePreferenceManager.saveFontSize(context, fontSize)
                currentFontSize.value = fontSize
                // 实时应用到 WebView（拖动时立即预览效果）
                webView.settings.textZoom = fontSize
            }
        )
    }
}
